package org.dtrd.modules.device.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.CheckUtil;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.device.config.DeviceConfigration;
import org.dtrd.modules.device.config.DeviceConstant;
import org.dtrd.modules.device.entity.bean.DeviceInfo;
import org.dtrd.modules.device.entity.bean.weice.WeiceResponse;
import org.dtrd.modules.device.entity.bean.weice.WeiceUpload;
import org.dtrd.modules.device.entity.bean.xty.XtyBaseResponse;
import org.dtrd.modules.device.entity.bean.xty.XtyNotifyStatusResponse;
import org.dtrd.modules.device.entity.bean.xty.XtySugarResponse;
import org.dtrd.modules.device.entity.po.*;
import org.dtrd.modules.device.entity.request.BindDeviceRequest;
import org.dtrd.modules.device.entity.request.DeviceRequest;
import org.dtrd.modules.device.entity.request.XtySugarRecordRequest;
import org.dtrd.modules.device.service.*;
import org.dtrd.modules.device.util.XtyDataUtil;
import org.dtrd.modules.record.service.IDtrdEntRdSigninBloodKetoneService;
import org.dtrd.modules.record.service.IDtrdEntRdSigninUricacidService;
import org.dtrd.modules.record.service.ISugarRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 萧
 * @date:2021-08-31 11:29 下午
 **/
@RestController
@Slf4j
@RequestMapping(value = {"/device", "900"})
@Api(tags = "智能设备")
public class DeviceController extends BaseController {

    @Autowired
    private IDtrdEntRdBiolandPushContentService biolandPushService;

    @Autowired
    private IDtrdEntRdXtyService xtyService;

    @Autowired
    private IDtrdEntRdXtyPushContentService xtyPushContentService;

    @Autowired
    private IDtrdEntRdDeviceService deviceService;

    @Autowired
    private IDtrdEntRdDevicePushContentService devicePushContentService;

    @Autowired
    private ISugarRecordService sugarRecordService;

    @Autowired
    private IDtrdEntRdSigninUricacidService uricacidService;

    @Autowired
    private IDtrdEntRdSigninBloodKetoneService bloodKetoneService;

    @ApiOperation("绑定设备")
    @PostMapping(value = "/bind")
    public Result<?> bindDevice(@RequestBody BindDeviceRequest request) {
        Integer patientId = request.getPatientId();
        if (isIntParamInvalid(patientId)) {
            Result error = error(SystemState.ResponseState.STATE_PARAMS_MISSING);
            error.setCode(error.getCode() + 1);
            return error;
        }
        // 序列号
        String deviceSn = request.getDeviceSn();
        if (CheckUtil.isEmpty(deviceSn)) {
            Result error = error(SystemState.ResponseState.STATE_PARAMS_MISSING);
            error.setCode(error.getCode() + 2);
            return error;
        }
        // 设备品牌
        Integer deviceBrand = request.getDeviceBrand();
        if (isIntParamInvalid(deviceBrand)) {
            Result error = error(SystemState.ResponseState.STATE_PARAMS_MISSING);
            error.setCode(error.getCode() + 3);
            return error;
        }
//        Result<?> result = deviceService.bindDevice(request);
//
//        if (DeviceConstant.DeviceBrand.isXty(deviceBrand)) {
//            // 小糖医
//            result = xtyService.bindDevice(request);
//        } else if (DeviceConstant.DeviceBrand.isBioland(deviceBrand)) {
//            // 爱奥乐
//            result = biolandService.bindDevice(request);
//        } else {
//            result = deviceService.bindDevice(request);
//        }
        return deviceService.bindDevice(request);
    }

    @GetMapping("/bioland")
    public String uploadBioland(@PathParam("data") String data) {
        return biolandPushService.onDataUpload(data);
    }

    @GetMapping("/xty")
    public String onXtyConfirm(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp, @PathParam("signature") String signature, @PathParam("echostr") String echostr) {
        log.info("DeviceController.onXtyConfirm.[nonce=" + nonce + ", timestamp=" + timestamp + ", signature=" + signature + ", echostr=" + echostr);
        if (CheckUtil.isEmpty(nonce) || CheckUtil.isEmpty(timestamp) || CheckUtil.isEmpty(signature) || CheckUtil.isEmpty(echostr)) {
            return "参数错误";
        }
        return xtyService.onXtyConfirm(nonce, timestamp, signature, echostr);
    }

    @PostMapping("/xty2")
    public String uploadXty(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
                            @PathParam("signature") String signature, @PathParam("echostr") String echostr,
                            @RequestBody JSONObject obj) {
        log.info("DeviceController.uploadXty [nonce=" + nonce + ", timestamp=" + timestamp + ", signature=" + signature + ", echostr=" + echostr + "; obj = " + obj);

        if (CheckUtil.isEmpty(nonce) || CheckUtil.isEmpty(timestamp) || CheckUtil.isEmpty(signature) || CheckUtil.isEmpty(echostr)) {
            return "参数错误";
        }
        if (XtyDataUtil.checkSignature(timestamp, nonce, signature)) {
            String msgId = obj.getString("msgId");
            DtrdEntRdXtyPushContent pushRecord = xtyPushContentService.getRecordByMsgId(msgId);
            if (pushRecord == null) {
                String msgType = obj.getString("msgType");
                String content = obj.getString("content");
                xtyPushContentService.savePushRecord(msgId, msgType, content);
                xtyService.onDataUpload(msgId, msgType, content);
            } else {
                log.info("DeviceController.uploadXty.[nonce, timestamp, signature, echostr, obj] timestamp=" + timestamp + ", signature=" + signature + "; 消息重复推送  不做处理");
            }
            return "success";
        } else {
            return "校验失败";
        }
    }

    @PostMapping("/xty")
    public String uploadXty(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
                            @PathParam("signature") String signature, HttpServletRequest request) {
        log.info("DeviceController.uploadXty with HttpRequest [nonce=" + nonce + ", timestamp=" + timestamp + ", signature=" + signature);

        if (CheckUtil.isEmpty(nonce) || CheckUtil.isEmpty(timestamp) || CheckUtil.isEmpty(signature)) {
            return "参数错误";
        }
        JSONObject obj = getJSONParams(request);
        log.info("DeviceController.uploadXty. with HttpRequest [nonce, timestamp, signature, echostr, request] obj =" + obj);
        if (XtyDataUtil.checkSignature(timestamp, nonce, signature)) {
            String msgId = obj.getString("msgId");
            DtrdEntRdXtyPushContent pushRecord = xtyPushContentService.getRecordByMsgId(msgId);
            if (pushRecord == null) {
                String msgType = obj.getString("msgType");
                String content = obj.getString("content");
                xtyPushContentService.savePushRecord(msgId, msgType, content);
                xtyService.onDataUpload(msgId, msgType, content);
            } else {
                log.info("DeviceController.uploadXty.[nonce, timestamp, signature, echostr, obj] timestamp=" + timestamp + ", signature=" + signature + "; 消息重复推送  不做处理");
            }
            return "success";
        } else {
            return "校验失败";
        }
    }

    @ApiOperation("激活小糖医推送")
    @GetMapping("/xty/active")
    public Result<?> activeXty() {
        XtyBaseResponse response = xtyService.activeXtyPush();
        return Result.OK(response);
    }

    @ApiOperation("关闭小糖医推送")
    @GetMapping("/xty/close")
    public Result<?> closeXty() {
        XtyBaseResponse response = xtyService.closeXtyPush();
        return Result.OK(response);
    }

    @ApiOperation("查询小糖医推送")
    @GetMapping("/xty/status")
    public Result<?> getXtyStatus() {
        XtyNotifyStatusResponse response = xtyService.getXtyStatus();
        return Result.OK(response);
    }

    @ApiOperation("查询小糖医血糖记录")
    @PostMapping("/xty/sugarrecord")
    public Result<?> getXtySugarRecord(@RequestBody XtySugarRecordRequest request) {
        XtySugarResponse response = xtyService.getXtySugarRecord(request);
        return Result.OK(response);
    }

    @ApiOperation("设备列表")
    @PostMapping("/list")
    public Result<List<DeviceInfo>> getDeviceList(@RequestBody @Validated  DeviceRequest request) {
        List<DeviceInfo> list = DeviceConfigration.getList();
        List<DeviceInfo> dataList = new ArrayList<>(3);
        if (list != null) {
            list.stream().filter(DeviceInfo::isEnable).forEach(deviceInfo -> {
                DeviceInfo item = new DeviceInfo(deviceInfo.isEnable(), deviceInfo.getDeviceIcon(),
                        deviceInfo.getDeviceName(), deviceInfo.getDeviceDescribe(), deviceInfo.getDeviceBrand(),
                        deviceInfo.getQrcodeLength(), deviceInfo.getDeviceCategory(), deviceInfo.getDeviceSn()
                );
                item.setPackageId(deviceInfo.getPackageId());
                DtrdEntRdDevice deviceVO = deviceService.getBindRecord(request.getPatientId(), deviceInfo.getDeviceBrand(), deviceInfo.getDeviceCategory());
                if (deviceVO != null) {
                    item.setDeviceSn(deviceVO.getDeviceSn());
                }
                dataList.add(item);
            });
        }
//        DeviceInfo xtyInfo = DeviceList.getXtyInfo();
//        if (xtyInfo != null) {
//            DtrdEntRdXty xtyPo = xtyService.getBindRecord(request.getPatientId());
//            if (xtyPo != null) {
//                xtyInfo.setDeviceSn(xtyPo.getDeviceSn());
//            } else {
//                xtyInfo.setDeviceSn(null);
//            }
//            list.add(xtyInfo);
//        }

//        DeviceInfo biolandInfo = DeviceList.getBiolandInfo();
//        if (biolandInfo != null) {
//            biolandInfo.setDeviceCategory(DeviceConstant.DeviceCategory.BLOODSUGAR.getCategory());
//            DtrdEntRdBioland biolandSugarPo = biolandService.getBindRecord(request.getPatientId(), DeviceConstant.DeviceCategory.BLOODSUGAR.getCategory());
//            if (biolandSugarPo != null) {
//                biolandInfo.setDeviceSn(biolandSugarPo.getDeviceSn());
//            } else {
//                biolandInfo.setDeviceSn(null);
//            }
//            list.add(biolandInfo);
//        }
//        if (DeviceConfigration.getList() != null) {
//            list.addAll(DeviceConfigration.getList());
//        }
        return Result.OK(dataList);
    }

    @ApiOperation("微策数据上传")
    @PostMapping(value = {"/weice/upload", "10/9001003"})
    public String onWeiceUpload(@RequestBody String body, @RequestHeader String signature) {
        boolean isValid = deviceService.checkWeiceSignature(signature, body);
        WeiceUpload request = JSONObject.parseObject(body, WeiceUpload.class);
        WeiceResponse response = new WeiceResponse();
        if (isValid) {
            // 保存推送记录
            DtrdEntRdDevicePushContent pushRecord = devicePushContentService.getPushRecordByMsgId(signature);
            response.success();
            if (pushRecord != null) {
                log.info("DeviceController.getApi.[request, signature] 推送记录已存在，signature=" + signature + "; request=" + request);
            } else {
                devicePushContentService.saveOrUpdateDevicePushContent(signature, request.getSn(), JSONUtil.toJsonStr(request), DeviceConstant.DeviceBrand.WEICE.getBrand(), DeviceConstant.DeviceCategory.BLOODSUGAR.getCategory());
                // 查找绑定记录 获取用户ID
                DtrdEntRdDevice dtrdEntRdDevice = deviceService.selectOntByDeviceSnAndDeviceType(request.getSn(), DeviceConstant.DeviceBrand.WEICE.getBrand(), DeviceConstant.DeviceCategory.BLOODSUGAR.getCategory());
                if (dtrdEntRdDevice != null) {
                    // 设备已绑定 ，保存相应检测记录
                    if (DeviceConstant.WeiceConfig.SampleType.isSugarRecord(request.getSample())) {
                        // 血糖
                        sugarRecordService.onWeiceSugarRecord(dtrdEntRdDevice.getUserId(), request.getValue(), request.getTimeType(), request.getMeasureTime(), request.getMeasureResult());
                    } else if (request.getSample() == DeviceConstant.WeiceConfig.SampleType.KETONE.getType()) {
                        // 血酮
                        bloodKetoneService.onWeiceRecord(dtrdEntRdDevice.getUserId(), request.getValue(), request.getMeasureTime(), request.getMeasureResult());
                    } else if (request.getSample() == DeviceConstant.WeiceConfig.SampleType.URICACID.getType()) {
                        // 尿酸
                        log.info("DeviceController.getApi.[request, signature] 尿酸数据=" + request);
                        uricacidService.onWeiceRecord(dtrdEntRdDevice.getUserId(), request.getValue(), request.getMeasureTime(), request.getMeasureResult());
                    } else {
                        response.failure(request.getSample(), "未知类型");
                        log.info("DeviceController.getApi.[request, signature] 未知类型 " + request.getSample());
                    }
                } else {
                    log.info("DeviceController.onWeiceUpload.[request, signature] 设备未绑定  deviceSn=" + request.getSn());
                }
            }
        } else {
            log.info("DeviceController.onWeiceUpload: {}, {} 数据校验失败", request, signature);
            response.onSignatureFailure("数据校验失败");
        }
        return JSONUtil.toJsonStr(response);
    }

}
